import sys
import traceback
import mysql.connector
from mysql.connector import Error
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
    QPushButton,QTabWidget,
    QMessageBox, QDialog,  QFormLayout,
    QLineEdit, QGroupBox
)
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import Qt

# 导入两个管理模块中的管理器类
from GUIdesign.Manage_customer_tap import AdminModule
from GUIdesign.Manage_card_tap import CardManagementTab


class AdminLogin(QDialog):
    """管理员登录对话框"""

    def __init__(self):
        super().__init__()
        self.setup_ui()

    def setup_ui(self):
        """初始化登录界面（调整为图片风格）"""
        # 设置窗口大小和背景
        self.setWindowTitle("银行管理系统")
        self.setFixedSize(800, 600)  # 调整为更合适的尺寸
        self.setStyleSheet("""
            QDialog {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1e5799, stop:1 #2989d8);
            }
            QLabel {
                color: white;
                font-size: 16px;
            }
            QLineEdit {
                background-color: white;
                border: 1px solid #d4d4d4;
                border-radius: 4px;
                padding: 8px;
                font-size: 14px;
                min-width: 200px;
            }
            QPushButton {
                background-color: #3498db;
                color: white;
                font-size: 16px;
                font-weight: bold;
                padding: 12px 24px;
                border-radius: 6px;
                border: none;
                min-width: 120px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)

        layout = QVBoxLayout()
        layout.setContentsMargins(50, 50, 50, 50)
        layout.setSpacing(30)

        # 主标题（与图片一致）
        title_label = QLabel("欢迎使用银行管理系统")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("""
            font-size: 28px; 
            font-weight: bold;
        """)
        layout.addWidget(title_label)

        # 登录表单
        form_layout = QFormLayout()
        form_layout.setSpacing(20)
        form_layout.setLabelAlignment(Qt.AlignRight)

        # 用户名输入
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("请输入管理员账户")

        # 密码输入
        self.password_edit = QLineEdit()
        self.password_edit.setPlaceholderText("请输入密码")
        self.password_edit.setEchoMode(QLineEdit.Password)

        form_layout.addRow("管理员:", self.username_edit)
        form_layout.addRow("密码:", self.password_edit)

        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.clicked.connect(self.authenticate)
        form_layout.addRow("", login_btn)  # 空标签使按钮居中

        layout.addLayout(form_layout)
        self.setLayout(layout)

        # 移除退出按钮以匹配图片简洁风格
        # 原有功能通过窗口系统按钮关闭保留

    def authenticate(self):
        """验证管理员凭据"""
        username = self.username_edit.text().strip()
        password = self.password_edit.text().strip()

        if not username:
            QMessageBox.warning(self, "输入错误", "请输入用户名")
            return

        if not password:
            QMessageBox.warning(self, "输入错误", "请输入密码")
            return

        # 检查用户名和密码
        if username == "admin" and password == "111111":
            self.accept()
        else:
            QMessageBox.warning(self, "登录失败", "用户名或密码错误")


class AdminDashboard(QMainWindow):
    """管理员主界面 - 整合客户管理和银行卡管理功能"""

    def __init__(self,welcome_screen =None):
        super().__init__()
        self.db = None
        self.setup_ui()
        self.connect_to_database()
        self.welcome_screen = welcome_screen  # 保存WelcomeScreen引用

    def setup_ui(self):
        """设置管理员界面UI"""
        self.setWindowTitle("银行系统 - 管理员面板")
        self.setMinimumSize(1100, 1200)
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f0f0;
            }
            QTabWidget::pane {
                border: 1px solid #d4d4d4;
                background: #f9f9f9;
            }
            QTabBar::tab {
                background: #e0e0e0;
                border: 1px solid #d4d4d4;
                border-bottom-color: #d4d4d4;
                padding: 10px 20px;
                margin-right: 2px;
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
                color: #555;
                font-size: 14px;
            }
            QTabBar::tab:selected {
                background: white;
                border-bottom: 1px solid white;
                color: #2980b9;
                font-weight: bold;
            }
            QTabBar::tab:hover {
                background: #f0f0f0;
            }
            QGroupBox {
                border: 1px solid #d4d4d4;
                border-radius: 5px;
                margin-top: 15px;
                padding: 15px;
                background-color: white;
                font-weight: bold;
            }
            QTableWidget {
                gridline-color: #d4d4d4;
            }
            QHeaderView::section {
                background-color: #f5f5f5;
                padding: 5px;
                border: 1px solid #d4d4d4;
            }
        """)

        # 创建主布局
        self.main_widget = QWidget()
        self.main_layout = QVBoxLayout(self.main_widget)
        self.main_layout.setContentsMargins(20, 20, 20, 20)
        self.main_layout.setSpacing(20)

        # 添加标题
        title_label = QLabel("银行系统 - 管理员面板")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 22px;
                font-weight: bold;
                color: #2c3e50;
                padding: 15px 0;
            }
        """)
        title_label.setAlignment(Qt.AlignCenter)
        self.main_layout.addWidget(title_label)

        # 创建标签页
        self.tab_widget = QTabWidget()

        # 添加客户管理模块
        self.customer_module = AdminModule()
        self.tab_widget.addTab(self.customer_module, "客户管理")

        # 添加银行卡管理模块 - 使用增强版
        self.card_module =CardManagementTab()
        self.tab_widget.addTab(self.card_module, "银行卡管理")

        self.main_layout.addWidget(self.tab_widget)

        # 添加状态栏
        self.status_bar = self.statusBar()
        self.status_bar.showMessage("就绪")

        # 添加退出按钮
        btn_layout = QHBoxLayout()
        refresh_btn = QPushButton("刷新数据")
        refresh_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)
        refresh_btn.setMinimumHeight(40)
        refresh_btn.clicked.connect(self.refresh_data)

        logout_btn = QPushButton("退出登录")
        logout_btn.setStyleSheet("""
            QPushButton {
                background-color: #95a5a6;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #7f8c8d;
            }
        """)
        logout_btn.setMinimumHeight(40)
        logout_btn.clicked.connect(self.logout)

        exit_btn = QPushButton("退出系统")
        exit_btn.setStyleSheet("""
            QPushButton {
                background-color: #e74c3c;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
        """)
        exit_btn.setMinimumHeight(40)
        exit_btn.clicked.connect(self.close)

        btn_layout.addWidget(refresh_btn)
        btn_layout.addWidget(logout_btn)
        btn_layout.addStretch(1)
        btn_layout.addWidget(exit_btn)
        self.main_layout.addLayout(btn_layout)

        self.setCentralWidget(self.main_widget)

        # 应用图标
        self.setWindowIcon(QIcon(":/icons/admin.png"))

    def connect_to_database(self):
        """连接数据库"""
        try:
            self.db = mysql.connector.connect(
                host='localhost',
                database='bank system',
                user='root',
                password='1234'
            )

            if self.db.is_connected():
                print("数据库连接成功")
                self.status_bar.showMessage("数据库连接成功", 3000)
                # 将数据库连接传递给各个模块
                if hasattr(self.customer_module, 'set_database'):
                    self.customer_module.set_database(self.db)
                if hasattr(self.card_module, 'set_database'):
                    self.card_module.set_database(self.db)

        except Error as e:
            QMessageBox.critical(self, "数据库错误", f"无法连接数据库: {str(e)}")
            self.status_bar.showMessage("数据库连接失败", 5000)

    def refresh_data(self):
        """刷新数据"""
        self.status_bar.showMessage("正在刷新数据...")
        QApplication.processEvents()  # 立即更新UI

        # 刷新客户管理模块
        if hasattr(self.customer_module, 'load_customer_data'):
            self.customer_module.load_customer_data()

        # 刷新银行卡管理模块
        if hasattr(self.card_module, 'load_card_data'):
            self.card_module.load_card_data()

        self.status_bar.showMessage("数据已刷新", 3000)

    def logout(self):
        """退出登录 - 修复版"""
        # 关闭数据库连接
        if self.db:
            try:
                self.db.disconnect()
                self.db = None
            except:
                pass

        # 关闭当前窗口
        self.close()

        # 如果存在 WelcomeScreen 引用，显示它
        if self.welcome_screen:
            self.welcome_screen.show()

    def closeEvent(self, event):
        """关闭窗口时释放资源"""
        if self.db and self.db.is_connected():
            self.db.close()
            print("数据库连接已关闭")
        event.accept()


def show_login_dialog():
    """显示登录对话框并返回管理员界面实例"""
    login_dialog = AdminLogin()
    if login_dialog.exec_() == QDialog.Accepted:
        admin_panel = AdminDashboard()
        admin_panel.show()
        return admin_panel
    return None


if __name__ == "__main__":
    # 全局异常处理
    def global_exception_hook(exctype, value, traceback_obj):
        """处理未捕获的异常"""
        error_msg = f"未捕获的异常: {exctype.__name__}, {str(value)}"
        print(error_msg)
        traceback.print_tb(traceback_obj)

        # 显示错误消息框
        app = QApplication.instance()
        if app is not None:
            QMessageBox.critical(None, "系统错误", error_msg)
        else:
            # 如果没有应用实例，创建一个临时实例
            temp_app = QApplication(sys.argv)
            QMessageBox.critical(None, "系统错误", error_msg)
            sys.exit(1)


    sys.excepthook = global_exception_hook

    app = QApplication(sys.argv)

    # 设置全局字体
    font = QFont()
    font.setFamily("Microsoft YaHei" if sys.platform == 'win32' else "Arial")
    font.setPointSize(11)
    app.setFont(font)

    # 显示登录对话框
    admin_panel = show_login_dialog()

    if admin_panel:
        sys.exit(app.exec_())
    else:
        sys.exit(0)